<?php

namespace App\Services;

use App\Helpers\ResponseHelper;
use App\Models\Order;
use App\Models\ProceedList;
use EasyWeChat\Factory;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Str;
use Overtrue\LaravelWeChat\Facade as EasyWeChat;
use SimpleSoftwareIO\QrCode\Facades\QrCode;

class OrderService
{
    // 生成订单号的逻辑
    public function generateOrderNumber($type): string
    {
        if ($type == 1) {
            $prefix = 'R';
        } elseif ($type == 2) {
            $prefix = 'O';
        } else {
            $prefix = 'E';
        }
        // 获取当前时间戳
        $timestamp = date('YmdHis');

        // 生成一个随机数
        $randomNumber = mt_rand(1000, 9999);

        // 组合生成订单号
        return $prefix . $timestamp . $randomNumber;
    }

    public function generateWriteOffCode($length = 6): string
    {
        $characters = 'ABCDEFGHIJKLMNPQRSTUVWXY0123456789';
        return collect(str_split($characters))
            ->random($length)
            ->implode('');
    }

    public function weChatPayment($user, $orderNumber, $amount, $type)
    {
        //return ResponseHelper::error(message: '微信支付失败');
        switch ($type) {
            case 1:
                $intro = '发布任务';
                break;
            case 2;
                $intro = '接单费用';
                break;
            default:
                $intro = '发布任务';
        }

        try {
            // 生成微信支付预支付订单
            $result = EasyWeChat::payment()->order->unify([
                'body' => $intro,
                'out_trade_no' => $orderNumber,
                'total_fee' => $amount * 100, // 金额，单位为分
                'notify_url' => config('wechat.payment.default.notify_url'), // 支付回调地址
                'trade_type' => 'JSAPI', // 小程序支付类型
                'openid' => $user->wx_open_id, // 用户的微信openid
            ]);
            if ($result['return_code'] === 'SUCCESS' && $result['result_code'] === 'SUCCESS') {
                // 返回前端用于调起支付的参数
                $jssdk = EasyWeChat::payment()->jssdk;
                $config = $jssdk->bridgeConfig($result['prepay_id'], false); // false表示不需要json格式

                return ResponseHelper::success(data: $config);
            } else {
                return ResponseHelper::error(message: $result['err_code_des'] ?? '微信支付失败');
            }
        } catch (\Exception $e) {
            return ResponseHelper::error(message: $e->getMessage());
        }
    }

    // 发起微信退款
    public function refund($orderNumber, $totalAmount, $refundAmount, $type)
    {
        // 进行退款
        $result = EasyWeChat::payment()->refund->byOutTradeNumber(
            $orderNumber, // 商户订单号
            'refund_' . $orderNumber . mt_rand(1000, 9999), // 商户退款单号
            $totalAmount * 100, // 订单金额（单位为分）
            $refundAmount * 100, // 退款金额（单位为分）
            [
                'refund_desc' => '商品退款', // 退款描述
            ]
        );
        // 检查退款结果
        if ($result['return_code'] === 'SUCCESS' && $result['result_code'] === 'SUCCESS') {
            /*$order = Order::where('order_number', $orderNumber)->first();
            if ($order) {
                $order->status = 7;
                $order->save();
            } else {
                $proceed = ProceedList::where('order_number', $orderNumber)->first();
                if ($proceed) {
                    $proceed->status = 3;
                }
            }
            // 更新订单状态为退款中
            $order->status = 'refunding';
            $order->refund_id = $result['refund_id'];
            $order->save();*/
            return ResponseHelper::success(message: '退款成功');
        } else {
            return ResponseHelper::error(message: $result['return_msg'] ?? '退款失败', data: $result);
        }
    }

    public function generateQrCode($code)
    {
        $fileName = 'images/qrcodes' . uniqid() . '_' . Str::random(10) . '.png';
        // 生成二维码并返回图片
        $qrCode = QrCode::size(128)->format('png')->generate($code);
        // 上传二维码到阿里云 OSS
        Storage::disk('oss')->put($fileName, $qrCode);

        // 返回二维码的 URL
        return $fileName;
    }

}
